// src/store/sealStore.ts
import { defineStore } from "pinia";
import { sealService } from "@/service/sealService";
// 引入类型（必须与接口、组件类型对齐）
import type {
  SealRecord,
  SealQueryParams,
  Pagination
} from "@/types/seal";

// 明确 Store 状态类型
interface SealState {
  sealRecords: SealRecord[];
  pagination: Pagination;
  loading: boolean;
  error: string | null;
  searchForm: SealQueryParams; // 保存搜索条件（关键：之前没定义！）
}

// 请求参数类型（与接口入参对齐）
interface FetchOptions extends SealQueryParams {
  page: number;
  pageSize: number;
}

export const useSealStore = defineStore("seal", {
  state: (): SealState => ({
    sealRecords: [],
    pagination: {
      page: 1,
      pageSize: 10,
      total: 0,
      totalPages: 0
    },
    loading: false,
    error: null,
    searchForm: {
      dateRange: [],
      sealType: "",
      handler: ""
    }, // 初始化搜索条件
  }),
  actions: {
    // 分页查询（完整类型推导）
    async fetchSealRecords(query: Partial<FetchOptions> = {}) {
      this.loading = true;
      this.error = null;
      try {
        const res = await sealService.getSealRecordsByPage(query);
        if (res.code === 200 && res.data) {
          this.sealRecords = res.data.list as SealRecord[];
          this.pagination = {
            page: res.data.page || 1,
            pageSize: res.data.pageSize || 10,
            total: res.data.total || 0,
            totalPages: res.data.totalPages || 0,
          };
        } else {
          this.error = res.msg || "查询印章记录失败";
        }
      } catch (err) {
        this.error = "网络异常，请检查后端服务";
        console.error("分页查询失败：", err);
      } finally {
        this.loading = false;
      }
    },

    // 搜索（参数类型与 searchForm 对齐）
    async searchSealRecords(searchForm: SealQueryParams) {
      this.searchForm = searchForm; // 保存搜索条件到 Store
      const query: FetchOptions = {
        page: 1,
        pageSize: this.pagination.pageSize,
        ...searchForm,
      };
      await this.fetchSealRecords(query);
    },

    // 新增（参数类型与 SealRecord 对齐）
    async addSealRecord(record: SealRecord, operator: string) {
      this.loading = true;
      this.error = null;
      try {
        const res = await sealService.addSealRecord(record, operator);
        if (res.code === 200) {
          await this.fetchSealRecords({
            page: this.pagination.page,
            pageSize: this.pagination.pageSize,
            ...this.searchForm, // 带上搜索条件，保持状态
          });
          return true;
        } else {
          this.error = res.msg || "新增记录失败";
          return false;
        }
      } catch (err) {
        this.error = "网络异常，新增失败";
        console.error("新增失败：", err);
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 编辑（参数类型与 SealRecord 对齐）
    async updateSealRecord(id: number, record: SealRecord, operator: string) {
      this.loading = true;
      this.error = null;
      try {
        const res = await sealService.updateSealRecord(id, record, operator);
        if (res.code === 200) {
          await this.fetchSealRecords({
            page: this.pagination.page,
            pageSize: this.pagination.pageSize,
            ...this.searchForm, // 带上搜索条件，保持状态
          });
          return true;
        } else {
          this.error = res.msg || "编辑记录失败";
          return false;
        }
      } catch (err) {
        this.error = "网络异常，编辑失败";
        console.error("编辑失败：", err);
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 删除（参数类型与接口对齐）
    async deleteSealRecord(id: number) {
      this.loading = true;
      this.error = null;
      try {
        const res = await sealService.deleteSealRecord(id);
        if (res.code === 200) {
          await this.fetchSealRecords({
            page: this.pagination.page,
            pageSize: this.pagination.pageSize,
            ...this.searchForm, // 带上搜索条件，保持状态
          });
          return true;
        } else {
          this.error = res.msg || "删除记录失败";
          return false;
        }
      } catch (err) {
        this.error = "网络异常，删除失败";
        console.error("删除失败：", err);
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 切换页码（参数类型 number）
    async changePage(page: number) {
      await this.fetchSealRecords({
        ...this.pagination,
        ...this.searchForm, // 带上搜索条件
        page,
      });
    },

    // 切换每页条数（参数类型 number）
    async changePageSize(pageSize: number) {
      await this.fetchSealRecords({
        page: 1,
        pageSize,
        ...this.searchForm, // 带上搜索条件
      });
    },

    // 清除错误（类型兼容）
    clearError() {
      this.error = null; // 直接赋 null，与 state 定义对齐
    },
  },
});
